﻿/* 
*  This file is part of the Unity networking tutorial by M2H (http://www.M2H.nl)
*  The original author of this code is Mike Hergaarden, even though some small parts 
*  are copied from the Unity tutorials/manuals.
*  Feel free to use this code for your own projects, drop us a line if you made something exciting! 
*/
#pragma strict
#pragma implicit
#pragma downcast

static var GUIMode : String =  "default";
static var playNowModeStarted  : float = 0.0;
static var myPlayerName : String = "MyPlayerName";

//GUI vars
private var hostPlayers : int = 8;
private var hostPort : int;
private var connectPort : int;
private var connectIP : String = "";

private var multiplayerScript : MenuMultiplayerCode;

var strMessage : String = "Click on quickplay to start playing right away!";

function Awake ()
{	
	Screen.lockCursor=false;	
	
	myPlayerName = PlayerPrefs.GetString("playerName");
	
	multiplayerScript = GetComponent(MenuMultiplayerCode);

	connectPort = hostPort = multiplayerScript.serverPort;
	connectIP = "127.0.0.1";
	
	GUIMode = "default";
}




function OnGUI ()
{
	var layoutListGames : Rect = Rect (25, 25, 260, 250);
	var layoutJoinGame : Rect = Rect (420, 25, 250, 100);
	var layoutHostGame : Rect = Rect (420, 140, 250, 100);
	var btnQuickPlay : Rect = Rect(300,180,150,30);
	var btnAdvanced : Rect = Rect(300,220,150,30);
	var lblPlayerName : Rect = Rect (100, 195, 250, 100);
	var btnBackMainMenu : Rect = Rect(250,280,200,40);
	var boxPlayerName : Rect = Rect (25, 180, 260, 105);
	var txtPlayerName : Rect = Rect (100, 215, 147, 27);
	var boxMessage : Rect = Rect(25,340,600,40);
	var btnCancel : Rect = Rect(300,300,75,20);
	var btnClose : Rect = Rect(300,300,75,20);
	
	GUI.Box(boxMessage, strMessage);

	//If we've connected;  load the game when it's ready to load
	if(Network.isClient || Network.isServer){
		//Since we're connected, load the game
		if(Application.CanStreamedLevelBeLoaded ((Application.loadedLevel+1))){
			strMessage = "Starting the game!";
			Application.LoadLevel((Application.loadedLevel+1));
		}else{
			strMessage = "Loading the game: "+Mathf.Floor(Application.GetStreamProgressForLevel((Application.loadedLevel+1))*100)+" %";
		}	
		return;
	}
	
	//Dirty error message popup
	if(multiplayerScript.errorMessage && multiplayerScript.errorMessage!=""){	
		strMessage = multiplayerScript.errorMessage;
		if(GUI.Button(btnClose, "Close")){
			multiplayerScript.errorMessage="";
		}
	}	
	switch (GUIMode)
	{
		case "PlayNowMode":
			playNowFunction();
			if(GUI.Button(btnCancel, "Cancel")){
				Network.Disconnect();
				strMessage = "Click on quickplay to start playing right away!";
				GUIMode = "default";
			}
			break;
		case "AdvancedMode":
			if(!multiplayerScript.errorMessage || multiplayerScript.errorMessage==""){ //Hide windows on error
				if(GUI.Button(btnBackMainMenu, "Back to main menu")){
					GUIMode = "default";
				}
				layoutListGames = GUILayout.Window (0, layoutListGames, listGUI, "Join a game via the list");	
				layoutJoinGame = GUILayout.Window (1, layoutJoinGame, directConnectGUIWindow, "Directly join a game via an IP");	
				layoutHostGame = GUILayout.Window (2, layoutHostGame, hostGUI, "Host a game");
			}	
			break;
		default:
			GUI.Box (boxPlayerName, "Playername");
			GUI.Label (lblPlayerName, "Please enter your name:");
			
			myPlayerName = GUI.TextField (txtPlayerName, myPlayerName);	
			if(GUI.changed){
				//Save the name changes
				PlayerPrefs.SetString("playerName", myPlayerName);
			}
			
			if(myPlayerName==""){
				strMessage = "After entering your name you can start playing!";
				return;
			}
			else
				strMessage = "Click on quickplay to start playing right away!";
			//btnQuickPlay		
			if(GUI.Button(btnQuickPlay, "Quickplay")){
				GUIMode = "PlayNowMode";
				playNowModeStarted=Time.time;
			}
			//btnAdvanced
			if(GUI.Button(btnAdvanced, "Advanced")){
				GUIMode = "AdvancedMode";
			}
			break;
	}
}


function playNowFunction()
{
	if(strMessage != "Failed to find a game")
		strMessage = multiplayerScript.PlayNow(playNowModeStarted);
	if(strMessage=="failed"){
		//Couldn't find a proper host; host ourselves
		Debug.Log("PlayNow: No games hosted, so hosting one ourselves");
		strMessage = "Failed to find a game";
		//multiplayerScript.StartHost(7, multiplayerScript.serverPort);		
	}
}


function hostGUI(id : int){

	GUILayout.BeginVertical();
	GUILayout.Space(10);
	GUILayout.EndVertical();
	
	GUILayout.BeginHorizontal();
	GUILayout.Space(10);
		GUILayout.Label("Use port: ");
		hostPort = parseInt(GUILayout.TextField(hostPort.ToString(), GUILayout.MaxWidth(75)));
	GUILayout.Space(10);
	GUILayout.EndHorizontal();	
	
	GUILayout.BeginHorizontal();
	GUILayout.Space(10);
		GUILayout.Label("Players: ");
		hostPlayers = parseInt(GUILayout.TextField(hostPlayers.ToString(), GUILayout.MaxWidth(75)));
	GUILayout.Space(10);
	GUILayout.EndHorizontal();
	
	
	GUILayout.BeginHorizontal();
	GUILayout.FlexibleSpace();
		// Start a new server
		if (GUILayout.Button ("Start hosting a server")){
			multiplayerScript.StartHost(hostPlayers, hostPort);
		}			
	GUILayout.FlexibleSpace();
	GUILayout.EndHorizontal();
}


function directConnectGUIWindow(id : int){

	GUILayout.BeginVertical();
	GUILayout.Space(5);
	GUILayout.EndVertical();
	GUILayout.Label(multiplayerScript.connectionInfo);
		
	if(multiplayerScript.nowConnecting){
		GUILayout.BeginHorizontal();
		GUILayout.FlexibleSpace();
		GUILayout.Label("Trying to connect to "+connectIP+":"+connectPort);
		GUILayout.FlexibleSpace();
		GUILayout.EndHorizontal();
		
	} else {		

		GUILayout.BeginHorizontal();
		GUILayout.Space(10);
			connectIP = GUILayout.TextField(connectIP, GUILayout.MinWidth(70));
			connectPort = parseInt(GUILayout.TextField(connectPort+""));
		GUILayout.Space(10);
		GUILayout.EndHorizontal();
		
		
		
		GUILayout.BeginHorizontal();
		GUILayout.Space(10);
		GUILayout.FlexibleSpace();
			
		if (GUILayout.Button ("Connect"))
		{
			multiplayerScript.Connect(connectIP, connectPort);
		}	
		
		GUILayout.FlexibleSpace();
		GUILayout.EndHorizontal();
	
	}
	
}

private var scrollPosition : Vector2;

function listGUI (id : int) {
	
		GUILayout.BeginVertical();
		GUILayout.Space(6);
		GUILayout.EndVertical();
	
		
		GUILayout.BeginHorizontal();
		GUILayout.Space(200);

		// Refresh hosts
		if (GUILayout.Button ("Refresh available Servers"))
		{
			multiplayerScript.FetchHostList(true);
		}
		multiplayerScript.FetchHostList(false);
		
		GUILayout.FlexibleSpace();
		GUILayout.EndHorizontal();

		scrollPosition = GUILayout.BeginScrollView (scrollPosition);

		var aHost : int = 0;
		
		if(multiplayerScript.sortedHostList && multiplayerScript.sortedHostList.length>=1){
			for (var myElement in multiplayerScript.sortedHostList)
			{
				var element=multiplayerScript.hostData[myElement];
				GUILayout.BeginHorizontal();

				// Do not display NAT enabled games if we cannot do NAT punchthrough
				if ( !(multiplayerScript.filterNATHosts && element.useNat) )
				{				
					aHost=1;
					var name = element.gameName + " ";
					GUILayout.Label(name);	
					GUILayout.FlexibleSpace();
					GUILayout.Label(element.connectedPlayers + "/" + element.playerLimit);
					
					if(element.useNat){
						GUILayout.Label(".");
					}
					GUILayout.FlexibleSpace();
					GUILayout.Label("[" + element.ip[0] + ":" + element.port + "]");	
					GUILayout.FlexibleSpace();
					if(!multiplayerScript.nowConnecting){
					if (GUILayout.Button("Connect"))
						{
							multiplayerScript.Connect(element.ip, element.port);
						}
					}else{
						GUILayout.Button("Connecting");
					}
					GUILayout.Space(15);
				}
				GUILayout.EndHorizontal();	
			}
		}		
		GUILayout.EndScrollView ();
		if(aHost==0){
			GUILayout.Label("No games hosted at the moment..");
		}
}
